package com.rankeiot.platform.util;

import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.rankeiot.core.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;

/**
 * @ClassName CacheUtil
 * @Description
 * @Author Focus
 * @Date 2023/3/9 18:19
 * @Version 1.0
 **/
@Slf4j
public class LocalCacheUtil {

    public static class Constants {

        public static final String SMS_CODE_FORGET_PHONENUMBER = "sms:code:forget:phone:phoneNumber";
        public static final String SMS_CODE_REGISTER_PHONENUMBER = "sms:code:register:phone:phoneNumber";
        public static final String SMS_CODE_LOGIN_PHONENUMBER = "sms:code:login:phone:phoneNumber";

    }


    /**
     * 默认缓存时长 5分钟
     */
    private static final long DEFAULT_TIMEOUT = 5 * DateUnit.MINUTE.getMillis();

    /**
     * 默认清理间隔时间 5分钟
     */
    private static final long CLEAN_TIMEOUT = 5 * DateUnit.MINUTE.getMillis();

    /**
     * 缓存对象
     */
    private static final TimedCache<String, Object> TIMED_CACHE = CacheUtil.newTimedCache(DEFAULT_TIMEOUT);

    static {
        //启动定时任务
        TIMED_CACHE.schedulePrune(CLEAN_TIMEOUT);
    }

    public static void set(String key, Object value) {
        TIMED_CACHE.put(key, value);
    }

    public static void set(String key, Object value, long expire) {
        TIMED_CACHE.put(key, value, expire);
    }

    //设置不过期的缓存,注意这里是内存,仅运行中设置后不过期
    public static void setNeverExpire(String key, Object value) {
        TIMED_CACHE.put(key, value, 0L);
    }

    /**
     * 获取并重新计算过期时间
     */
    public static Object getWithUpdateLastAccess(String key) {
        return TIMED_CACHE.get(key);
    }

    /**
     * 获取
     *
     * @param key
     * @return
     */
    public static Object get(String key) {
        return TIMED_CACHE.get(key, false);
    }

    /**
     * 获取String
     *
     * @param key
     * @return
     */
    public static String getString(String key) {
        return (String) TIMED_CACHE.get(key, false);
    }

    /**
     * 缓存验证
     *
     * @return boolean
     * @Param [captcha, cpId]
     **/
    public static boolean verify(String key, String verifyValue) {
        if (StrUtil.isAllEmpty(key, verifyValue)) {
            throw new BusinessException("缓存验证参数为空");
        }
        String cacheValue = (String) get(key);
        if (StrUtil.isEmpty(cacheValue)) {
            throw new BusinessException("缓存不存在");
        }
        if (!ObjectUtil.equal(verifyValue, cacheValue)) {
            throw new BusinessException("验证失败");
        }
        return true;
    }


    public static Set<String> keySet() {
        return TIMED_CACHE.keySet();
    }


    public static void remove(String key) {
        TIMED_CACHE.remove(key);
    }

    public static void clear() {
        TIMED_CACHE.clear();
    }


}
